﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System.Collections.Generic;
using System.Linq;
using FinPlusAssembler;
using FinPlusInterfaces;
using FinPlusCompCore;

namespace FinPlusCompProxy
{
    public class QLAnalytics : FinPlusComponent
    {
        [State(Test = true)]
        public override bool IsValid { get; set; }
        [State(Test = true)]
        public override string TestString { get { return Adapter.ToString(); } }
        public override IPods Adapter { get { return _instrumentConn.Adapter; } }
 
        public ql QL { get { return _ql; } } 
        public string MarketName { get; private set; }
        public string CacheName { get; private set; }
        public string DiscountCurve { get; private set; }
        public int AsOf { get; private set; }
        public string BuySell { get; private set; }
        public IDictionary<string, string> Infos { get; private set; }
        public IDictionary<string, string> Controls { get; private set; }
        public IDictionary<string, int> Shocks { get; private set; }
        public string ControlString { get; set; }
        public bool HasControlString { get; set; }

        private enum Params { LevelUpdate, Request, Resend, Refresh, Shock }
        private readonly IFinPlusComp _instrumentConn;
        private readonly static ql _ql = new ql();
        private static IPod _pod;
        
        //construct
        public QLAnalytics(IFinPlusComp instruments, string marketName, string cacheName, int asOf, string discountCurve, 
            string buySell, IDictionary<string, string> infos, IDictionary<string, string> controls, IDictionary<string, int> shocks) 
        {
            IsValid = true;
            _instrumentConn = instruments;
            MarketName = marketName;
            CacheName = cacheName;
            BuySell = buySell;
            DiscountCurve = discountCurve;
            AsOf = asOf;
            Infos =infos;
            Controls = controls;
            ControlString = string.Join(",", Controls.Select(f => f.Key).ToArray());
            HasControlString = !string.IsNullOrEmpty(ControlString);
            Shocks = shocks;

            lock (QL)
                QL.MarketSet(MarketName, AsOf);

            if (_pod == null)
            {
                _pod = IOC.New<IPod>("QL", "ql");
                _pod.Object = QL;
                _pod.Type = QL.GetType();
            }
        }

        //common control interface
        public override void Dispose() 
        {
            if (_instrumentConn != null)
                _instrumentConn.Dispose();
        }

        public string InvokeMethod(IPod pod, Env env, IList<string> exclude = null)
        {

            var res = pod.InvokeMethod(_pod, exclude);
            return res.ToString();
        }
    }
}
